package bsh.dyn;

import java.util.HashMap;
import java.util.Map;

import bsh.CompiledScript;

/**
 * Invocable that contains a group of Invocables, each associated with a unique callsite id. Callsites that share an id but differs on some
 * class type should not be colapsed together
 * 
 * @author takeshi
 */
public class CollapsedInvocableImpl implements ColapsedInvocable {

    private final Map<Integer, Invocable> invocables;

    /**
     * Constructor
     * 
     * @param invocables a {@link Map} of callsite id to invocable. This map is copied to this {@link ColapsedInvocable} so further
     * modifications on the map don't reflect on this {@link ColapsedInvocable}
     */
    public CollapsedInvocableImpl(Map<Integer, Invocable> invocables) {
        super();
        this.invocables = new HashMap<Integer, Invocable>(invocables);
    }

    /**
     * {@inheritDoc}
     */
    public Object invoke(int callsiteId, CompiledScript script, Object target, Object[] parameters) throws Throwable {
        Invocable inv = this.invocables.get(callsiteId);
        if (inv != null) {
            return inv.invoke(script, target, parameters);
        }
        throw new IllegalArgumentException();
    }

}
